package filter;

import beans.User;
import jakarta.servlet.*;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import service.UserService;
import utils.CookieUtils;

import java.io.IOException;

public class AutoLoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //0.将request，reponse向下转型，为了使用HttpServletRequest，HttpServletResponse里面的api
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //1.判断用户登录状态(判断Session中是否有用户)
        User existUser = (User)req.getSession().getAttribute("existUser");
        if (existUser!=null) {
            //有，用户依然是登录状态，没必要利用过滤器还原会话状态，直接放行
            chain.doFilter(req, resp);
        }else {
            //没有会话状态
            Cookie cookie = CookieUtils.getCookie("autoLogin", req.getCookies());
            if (cookie==null) {
                //如果没找到name未autoLogin，说明用户登录时候没有勾选记住我，放行
                chain.doFilter(req, resp);
            }else {
                String[] values = cookie.getValue().split("#");
                //从cookie中取出用户名和密码，更具用户名与密码查询数据库
                UserService userService = new UserService();
                User user = userService.login(new User(values[0], values[1]));
                if (user==null) {
                    //说明没查到cookie中用户名和密码，数据信息被篡改
                    chain.doFilter(req, resp);
                } else {
                    //查到将用户信息存入session，会话状态回复，放行
                    req.getSession().setAttribute("existUser", user);
                    chain.doFilter(req, resp);
                }
            }
        }

    }
}
